package com.dream.myqiyi.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;
import com.baidu.mapapi.OverlayItem;
import com.dream.myqiyi.R;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.dao.NotebookModel;
import com.dream.myqiyi.dao.TagModel;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteService;
import com.dream.myqiyi.service.NotebookService;
import com.dream.myqiyi.service.TagService;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class NoteInfoActivity extends MapActivity {

	public static final int NOTEBOOK_SELECTED_RESULT = 200;
	public static final int TAG_SELECTED_RESULT = 201;

	private NoteModel note = null;
	private NotebookModel notebook = null;
	private List<TagModel> tags = null;
	
	private TextView notebookInfoTv = null;
	private TextView tagInfoTv = null;
	
	private TextView createdTv = null;
	private TextView updatedTv = null;
	
	private ScrollView infoSv;
	
	//添加百度地图的相关控件
	private MapView mapView;
	//加载地图的引擎
	private BMapManager bMapManager;
	//private MKSearch mSearch = null;
	//百度地图的key
	private String KeyString = "8C426377B3526B6BF3672C9BA3BB544D1E8289CD";
	//在百度地图上添加一些控件,比如是放大或者缩小的控件
	private MapController mapController;
	//定位图层
	MyLocationOverlay mLocationOverlay = null;
	//onResume时注册此listener，onPause时需要Remove
	LocationListener mLocationListener = null;

	//private ImageButton mRetIB;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.note_info_view);
        
        initUI();
        
        initData();
        
	}
	
	private void initUI() {
        findViewById(R.id.ret_btn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(NoteInfoActivity.this, NoteViewActivity.class);
				Bundle newBundle = new Bundle();
				newBundle.putBoolean("info_change", false);
				intent.putExtras(newBundle);
				NoteInfoActivity.this.setResult(NoteViewActivity.INFO_RESULT, intent);
				NoteInfoActivity.this.finish();
			}
		});
		
		notebookInfoTv = (TextView)findViewById(R.id.notebook_info_tv);
		tagInfoTv = (TextView)findViewById(R.id.tag_info_tv);
		tagInfoTv.requestFocus();

		findViewById(R.id.note_info_page_notebook).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NoteInfoActivity.this, NotebookSelectActivity.class);
				//Bundle bundle = new Bundle();
				//bundle.putString("notebook_guid", notebook.getGuid());
				//intent.putExtras(bundle);
				startActivityForResult(intent, NOTEBOOK_SELECTED_RESULT);
			}
			
		});
		
		findViewById(R.id.note_info_page_tag).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(NoteInfoActivity.this, TagSelectActivity.class);
				//Bundle bundle = new Bundle();
				//bundle.putString("notebook_guid", notebook.getGuid());
				//intent.putExtras(bundle);
				startActivityForResult(intent, TAG_SELECTED_RESULT);
			}
			
		});
		
		createdTv = (TextView)findViewById(R.id.created_tv);
		updatedTv = (TextView)findViewById(R.id.updated_tv);
		
		
        mapView = (MapView) this.findViewById(R.id.bmapView);
        bMapManager = new BMapManager(NoteInfoActivity.this	);
        //必须要加载key
        bMapManager.init(KeyString, new MKGeneralListener() {

			public void onGetPermissionState(int arg0) {
				if(arg0==300){
					Toast.makeText(NoteInfoActivity.this, "输入的key有错，请核实！！", Toast.LENGTH_SHORT).show();
				}
			}

			public void onGetNetworkState(int arg0) {

			}
		});
        this.initMapActivity(bMapManager);
        //表示可以设置缩放功能
        mapView.setBuiltInZoomControls(true);
        mapController = mapView.getController();
        //设置缩放级别是12个级别
        mapController.setZoom(12);

        Drawable drawable = getResources().getDrawable(R.drawable.bmap_mark_a);
        mapView.getOverlays().add(new MyOverLayItem(drawable));

		// 添加定位图层
        mLocationOverlay = new MyLocationOverlay(this, mapView);
        mapView.getOverlays().add(mLocationOverlay);

        // 注册定位事件
        mLocationListener = new LocationListener() {

			@Override
			public void onLocationChanged(Location location) {
				if (location != null){
					GeoPoint pt = new GeoPoint((int)(location.getLatitude()*1e6),
											   (int)(location.getLongitude()*1e6));
					mapController.animateTo(pt);
				}
			}
        };		
        //mTitleView.setText(R.string.category_account);	
        
        infoSv = (ScrollView)findViewById(R.id.note_info_scroll);
    	infoSv.post(new Runnable() {  
            public void run() {  
            	infoSv.fullScroll(ScrollView.FOCUS_UP);  
            }  
    	});  
	}
	
	private void initData() {
		NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
		note = noteSrv.getCurrNoteModel();

		updateNotebookInfo();
		updateTagInfo();
		
		createdTv.setText(new Date(note.getCreated()).toLocaleString());
		updatedTv.setText(new Date(note.getUpdated()).toLocaleString());

	}
	
	private void updateNotebookInfo() {
		if (note == null) {
			return ;
		}
		NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
		if (nbSrv == null) {
			return ;
		}
		notebook = nbSrv.getNotebook(note.getNotebookGuid());
		if (notebook == null) {
			notebook = nbSrv.getCurrNotebook();
		}
		notebookInfoTv.setText(notebook.getName());
	}
	
	private void updateTagInfo() {
		if (note == null) {
			return ;
		}
		TagService tagSrv = (TagService)ApplicationContext.getSingleton().getBean("TagService");
		if (tagSrv == null) {
			return ;
		}
		tags = tagSrv.getNoteTags(note.getGuid());
		if (tags == null) {
			return ;
		}
		String tagsDisp = "";
		boolean isFirst = true;
		for (TagModel tag : tags) {
			if (isFirst) {
				tagsDisp += tag.getName();
				isFirst = false;
			} else {
				tagsDisp += "; " + tag.getName();
			}
		}
		tagInfoTv.setText(tagsDisp);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case NOTEBOOK_SELECTED_RESULT:
			updateNotebookInfo();
			break;
		case TAG_SELECTED_RESULT:
			updateTagInfo();
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
		
    	infoSv.post(new Runnable() {  
            public void run() {  
            	infoSv.fullScroll(ScrollView.FOCUS_UP);  
            }  
    	});  
	}


    public class MyOverLayItem extends ItemizedOverlay<OverlayItem>{

    	private List<OverlayItem> list = new ArrayList<OverlayItem>();
    	//以double类型定义一组坐标
    	private double mLat1 = 39.90923;//表示为纬度
    	private double mLon1 = 116.397428;//表示经度

    	private double mLat2 = 39.9022;//表示为纬度
    	private double mLon2 = 116.3922;//表示经度

    	private double mLat3 = 39.9033;//表示为纬度
    	private double mLon3 = 116.3933;//表示经度

    	//用于在地图上标识坐标,用一个图片标注
		public MyOverLayItem(Drawable arg0) {
			super(arg0);
			//第一组数据在地图上的标注点
			GeoPoint geoPoint1  = new GeoPoint((int)(mLat1*1E6),(int)(mLon1*1E6));
			//第二组数据在地图上的标注点
			GeoPoint geoPoint2  = new GeoPoint((int)(mLat2*1E6),(int)(mLon2*1E6));
			//第三组数据在地图上的标注点
			GeoPoint geoPoint3  = new GeoPoint((int)(mLat3*1E6),(int)(mLon3*1E6));
			//标注点,标题,片段
			list.add(new OverlayItem(geoPoint1,"point1","point1"));
			list.add(new OverlayItem(geoPoint2,"point2","point2"));
			list.add(new OverlayItem(geoPoint3,"point3","point3"));
			populate();//实现了地图刷新的功能

		}

		//返回指定的list集合中每一个坐标
		@Override
		protected OverlayItem createItem(int arg0) {
			return list.get(arg0);
		}

		//返回list集合中坐标的个数
		@Override
		public int size() {
			return list.size();
		}

		@Override
		public boolean onTap(int i) {
			Toast.makeText(NoteInfoActivity.this, list.get(i).getSnippet(), Toast.LENGTH_SHORT).show();
			return true;
		}

    }


    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	if(bMapManager!=null){
    		bMapManager.destroy();
    		bMapManager = null;
    	}
    }

    @Override
    protected void onResume() {
    	super.onResume();
    	if(bMapManager!=null){
    		// 注册定位事件，定位后将地图移动到定位点
    		bMapManager.getLocationManager().requestLocationUpdates(mLocationListener);
            mLocationOverlay.enableMyLocation();
            mLocationOverlay.enableCompass(); // 打开指南针

    		bMapManager.start();
    	}
    	infoSv.post(new Runnable() {  
            public void run() {  
            	infoSv.fullScroll(ScrollView.FOCUS_UP);  
            }  
    	});  
    	
    }

    @Override
    protected void onPause() {
    	super.onPause();
    	if(bMapManager!=null) {
    		bMapManager.getLocationManager().removeUpdates(mLocationListener);
    		mLocationOverlay.disableMyLocation();
            mLocationOverlay.disableCompass(); // 关闭指南针

    		bMapManager.stop();
    	}
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

}
